package com.sddnytsh.body_buildingsystem.screens

import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.gestures.snapping.SnapPosition
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.Send
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material.icons.filled.Send
import androidx.compose.material3.Button
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.material3.TextFieldDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.navigation.NavController
import com.google.firebase.crashlytics.buildtools.reloc.com.google.common.reflect.TypeToken
import com.google.gson.Gson
import com.sddnytsh.body_buildingsystem.R
import com.sddnytsh.body_buildingsystem.components.CommentInputSection
import com.sddnytsh.body_buildingsystem.components.CommentItem
import com.sddnytsh.body_buildingsystem.components.PostContentSection
import com.sddnytsh.body_buildingsystem.topic.Comment
import com.sddnytsh.body_buildingsystem.topic.Post
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import okhttp3.FormBody
import okhttp3.OkHttpClient
import okhttp3.Request
import java.io.IOException

//@Composable
//fun PostDetailScreen(navController: NavController, postId: Int) {
//    val post = remember(postId) {
//        Post(
//            id = postId,
//            author = "运动达人",
//            avatarRes = R.drawable.person,
//            title = "分享我的跑步经验",
//            content = "坚持跑步3年了，从最初的3公里到现在能轻松跑完半马。最重要的是保持节奏，不要一开始就跑太快。\n\n建议新手可以从慢跑开始，每周3-4次，每次20-30分钟，逐渐增加距离和速度。跑步时注意呼吸节奏，保持身体放松。",
//            time = "2小时前",
//            likeCount = 24,
//            favoriteCount = 8,
//            commentCount = 5
//        )
//    }
//
//    var comments by remember {
//        mutableStateOf(
//            listOf(
//                Comment(
//                    id = 1,
//                    author = "跑步爱好者",
//                    avatarRes = R.drawable.person,
//                    content = "说得很好！我也是从3公里开始，现在能跑10公里了",
//                    time = "1小时前",
//                    likeCount = 3
//                ),
//                Comment(
//                    id = 2,
//                    author = "健身新手",
//                    avatarRes = R.drawable.person,
//                    content = "请问需要什么装备？跑鞋有推荐吗？",
//                    time = "45分钟前",
//                    likeCount = 1
//                ),
//                Comment(
//                    id = 3,
//                    author = "马拉松跑者",
//                    avatarRes = R.drawable.person,
//                    content = "补充一点：跑前热身和跑后拉伸非常重要，可以避免受伤",
//                    time = "30分钟前",
//                    likeCount = 5
//                )
//            )
//        )
//    }
//
//    var newComment by remember { mutableStateOf("") }
//
//    Column(modifier = Modifier.fillMaxSize()) {
//        Box(
//            modifier = Modifier
//                .fillMaxWidth()
//                .height(56.dp)
//                .background(Color.White)
//                .padding(horizontal = 16.dp)
//        ) {
//            Icon(
//                imageVector = Icons.Default.ArrowBack,
//                contentDescription = "返回",
//                modifier = Modifier
//                    .size(24.dp)
//                    .align(Alignment.CenterStart)
//                    .clickable {
//                        navController.popBackStack()
//                    }
//            )
//            Text(
//                text = "帖子详情",
//                style = MaterialTheme.typography.titleMedium.copy(fontWeight = FontWeight.Bold),
//                modifier = Modifier.align(Alignment.Center)
//            )
//        }
//
//        Column(
//            modifier = Modifier
//                .fillMaxWidth()
//                .background(Color(0xFFF5F5F5))
//        ) {
//            // 内容区域（可滚动）
//            LazyColumn(
//                modifier = Modifier
//                    .weight(1f)
//                    .padding(horizontal = 8.dp)
//                    .background(Color(0xFFF5F5F5))
//            ) {
//                // 帖子内容
//                item {
//                    PostContentSection(post = post)
//                    Spacer(modifier = Modifier.height(8.dp))
//                }
//
//                // 评论标题
//                item {
//                    Text(
//                        text = "评论 (${comments.size})",
//                        modifier = Modifier.padding(horizontal = 16.dp, vertical = 12.dp)
//                    )
//                }
//
//                // 评论列表
//                items(comments.size) { index ->
//                    val comment = comments[index]
//                    CommentItem(comment = comment)
//                    Spacer(modifier = Modifier.height(8.dp))
//                }
//
//                // 底部空白，避免被输入框遮挡
//                item {
//                    Spacer(modifier = Modifier.height(60.dp))
//                }
//            }
//        }
//
//        Box(
//            modifier = Modifier
//                .fillMaxWidth()
//                .background(Color.White)
//        ) {
//            CommentInputSection(
//                commentText = newComment,
//                onCommentChange = { newComment = it },
//                onSendComment = {
//                    if (newComment.isNotBlank()) {
//                        val newCommentObj = Comment(
//                            id = comments.size + 1,
//                            author = "当前用户",
//                            avatarRes = R.drawable.person,
//                            content = newComment,
//                            time = "刚刚",
//                            likeCount = 0
//                        )
//                        comments = comments + newCommentObj
//                        newComment = ""
//                    }
//                }
//            )
//        }
//    }
//}

@Composable
fun PostDetailScreen(navController: NavController, postId: Int) {
    // 状态管理
    var post by remember { mutableStateOf<Post?>(null) }
    var comments by remember { mutableStateOf<List<Comment>>(emptyList()) }
    var isLoading by remember { mutableStateOf(true) }
    var errorMessage by remember { mutableStateOf<String?>(null) }
    var newComment by remember { mutableStateOf("") }

    // 从API获取帖子详情和评论
    LaunchedEffect(postId) {
        isLoading = true
        errorMessage = null

        try {
            // 获取帖子详情
            val postResponse = getPostById(postId)
            post = postResponse

            // 获取评论列表
            val commentsResponse = getCommentsByPostId(postId)
            comments = commentsResponse
        } catch (e: Exception) {
            errorMessage = "加载失败: ${e.message}"
        } finally {
            isLoading = false
        }
    }

    Column(modifier = Modifier.fillMaxSize()) {
        // 顶部导航栏
        Box(
            modifier = Modifier
                .fillMaxWidth()
                .height(56.dp)
                .background(Color.White)
                .padding(horizontal = 16.dp)
        ) {
            Icon(
                imageVector = Icons.Default.ArrowBack,
                contentDescription = "返回",
                modifier = Modifier
                    .size(24.dp)
                    .align(Alignment.CenterStart)
                    .clickable {
                        navController.popBackStack()
                    }
            )
            Text(
                text = "帖子详情",
                style = MaterialTheme.typography.titleMedium.copy(fontWeight = FontWeight.Bold),
                modifier = Modifier.align(Alignment.Center)
            )
        }

        // 加载状态
        if (isLoading) {
            Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
                CircularProgressIndicator()
            }
        }
        // 错误状态
        else if (errorMessage != null) {
            Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
                Column(horizontalAlignment = Alignment.CenterHorizontally) {
                    Text(text = errorMessage ?: "未知错误")
                    Spacer(modifier = Modifier.height(16.dp))
                    Button(onClick = {
                        // 重新加载数据
                        isLoading = true
                        errorMessage = null
                    }) {
                        Text(text = "重试")
                    }
                }
            }
        }
        // 正常显示内容
        else if (post != null) {
            Column(
                modifier = Modifier
                    .fillMaxWidth()
                    .background(Color(0xFFF5F5F5))
            ) {
                // 内容区域（可滚动）
                LazyColumn(
                    modifier = Modifier
                        .weight(1f)
                        .padding(horizontal = 8.dp)
                        .background(Color(0xFFF5F5F5))
                ) {
                    // 帖子内容
                    item {
                        PostContentSection(
                            post = post!!,
                        )
                        Spacer(modifier = Modifier.height(8.dp))
                    }

                    // 评论标题
                    item {
                        Text(
                            text = "评论 (${comments.size})",
                            modifier = Modifier.padding(horizontal = 16.dp, vertical = 12.dp),
                            style = MaterialTheme.typography.titleSmall.copy(fontWeight = FontWeight.SemiBold)
                        )
                    }

                    // 评论列表
                    if (comments.isEmpty()) {
                        item {
                            Box(
                                modifier = Modifier
                                    .fillMaxWidth()
                                    .padding(vertical = 32.dp),
                                contentAlignment = Alignment.Center
                            ) {
                                Text(
                                    text = "暂无评论，快来发表第一条评论吧~",
                                    color = Color.Gray
                                )
                            }
                        }
                    } else {
                        items(comments) { comment ->
                            CommentItem(
                                comment = comment,
                            )
                            Spacer(modifier = Modifier.height(8.dp))
                        }
                    }

                    // 底部空白，避免被输入框遮挡
                    item {
                        Spacer(modifier = Modifier.height(60.dp))
                    }
                }
            }

            // 评论输入框
            Box(
                modifier = Modifier
                    .fillMaxWidth()
                    .background(Color.White)
            ) {
                CommentInputSection(
                    commentText = newComment,
                    onCommentChange = { newComment = it },
                    onSendComment = {
                        if (newComment.isNotBlank()) {
                            // 发送评论到API
                            CoroutineScope(Dispatchers.IO).launch {
                                try {
                                    val response = addComment(postId, newComment)
                                    if (response.success) {
                                        // 评论成功，刷新评论列表
                                        val updatedComments = getCommentsByPostId(postId)
                                        withContext(Dispatchers.Main) {
                                            comments = updatedComments
                                            newComment = ""
                                            // 更新帖子评论数量
                                            post = post?.copy(commentCount = post!!.commentCount + 1)
                                        }
                                    } else {
                                        withContext(Dispatchers.Main) {
                                            errorMessage = response.message ?: "评论发送失败"
                                        }
                                    }
                                } catch (e: Exception) {
                                    withContext(Dispatchers.Main) {
                                        errorMessage = "评论发送失败: ${e.message}"
                                    }
                                }
                            }
                        }
                    }
                )
            }
        }
    }
}

// 获取帖子详情的函数
suspend fun getPostById(postId: Int): Post {
    return withContext(Dispatchers.IO) {
        // 这里替换为您的实际API端点
        val url = "https://10.203.132.164:8082/api/community-posts/user/{userId}"

        val client = OkHttpClient()
        val request = Request.Builder()
            .url(url)
            .build()

        client.newCall(request).execute().use { response ->
            if (!response.isSuccessful) {
                throw IOException("Unexpected code $response")
            }

            val responseBody = response.body?.string()
            // 解析JSON响应为Post对象
            // 这里需要根据您的API响应格式进行解析
            // 示例使用Gson，您可以使用任何JSON解析库
            val gson = Gson()
            gson.fromJson(responseBody, Post::class.java)
        }
    }
}

// 获取评论列表的函数
suspend fun getCommentsByPostId(postId: Int): List<Comment> {
    return withContext(Dispatchers.IO) {
        // 这里替换为您的实际API端点
        val url = "https://10.203.132.164:8082/api/post-comments/post/{postId}"

        val client = OkHttpClient()
        val request = Request.Builder()
            .url(url)
            .build()

        client.newCall(request).execute().use { response ->
            if (!response.isSuccessful) {
                throw IOException("Unexpected code $response")
            }

            val responseBody = response.body?.string()
            // 解析JSON响应为Comment列表
            // 这里需要根据您的API响应格式进行解析
            val gson = Gson()
            val type = object : TypeToken<List<Comment>>() {}.type
            gson.fromJson(responseBody, type)
        }
    }
}

// 发送评论的函数
suspend fun addComment(postId: Int, content: String): ApiResponse {
    return withContext(Dispatchers.IO) {
        // 这里替换为您的实际API端点
        val url = "https://10.203.132.164:8082/api/post-comments"

        // 创建请求体
        val requestBody = FormBody.Builder()
            .add("content", content)
            .build()

        val client = OkHttpClient()
        val request = Request.Builder()
            .url(url)
            .post(requestBody)
            .build()

        client.newCall(request).execute().use { response ->
            if (!response.isSuccessful) {
                throw IOException("Unexpected code $response")
            }

            val responseBody = response.body?.string()
            // 解析JSON响应为ApiResponse对象
            val gson = Gson()
            gson.fromJson(responseBody, ApiResponse::class.java)
        }
    }
}

// 评论输入组件
@Composable
fun CommentInputSection(
    commentText: String,
    onCommentChange: (String) -> Unit,
    onSendComment: () -> Unit
) {
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .padding(horizontal = 16.dp, vertical = 8.dp),
        verticalAlignment = Alignment.CenterVertically
    ) {
        OutlinedTextField(
            value = commentText,
            onValueChange = onCommentChange,
            modifier = Modifier
                .weight(1f)
                .heightIn(min = 40.dp),
            placeholder = { Text("写一条评论...") },
            singleLine = true
        )

        Spacer(modifier = Modifier.width(8.dp))

        IconButton(
            onClick = onSendComment,
            enabled = commentText.isNotBlank()
        ) {
            Icon(
                imageVector = Icons.Default.Send,
                contentDescription = "发送评论",
                tint = if (commentText.isNotBlank()) Color.Black else Color.Gray
            )
        }
    }
}

// API响应数据类
data class ApiResponse(val success: Boolean, val message: String? = null)